package jumpingnotes.service.remoting;

import java.util.Date;
import java.util.List;

import jumpingnotes.model.ErrorType;
import jumpingnotes.model.Result;
import jumpingnotes.model.entity.Activity;
import jumpingnotes.model.entity.ActivityMediaItem;
import jumpingnotes.model.entity.ActivityTemplate;
import jumpingnotes.model.entity.ActivityTemplateParam;
import jumpingnotes.model.entity.Member;
import jumpingnotes.service.AccessService;
import jumpingnotes.service.QueryService;

public class GenericService {
	AccessService accessService;
	QueryService queryService;
	
	public void setAccessService(AccessService accessService) {
		this.accessService = accessService;
	}
	
	public void setQueryService(QueryService queryService) {
		this.queryService = queryService;
	}	
	
	public Result memberActivityCreate(String memberID,
			String activityType, ActivityTemplateParam[] activityParams,
			ActivityMediaItem[] mediaItems, String url, String priority) {
		// TODO Auto-generated method stub
		Member member = accessService.findMemberById(Integer.parseInt(memberID));
		if(member == null)
			return new Result(ErrorType.USER_NOT_EXIST);
		
		ActivityTemplate exampleActivityTemplate = new ActivityTemplate();
		exampleActivityTemplate.setType(activityType);
		List<ActivityTemplate> list = accessService.findAllActivityTemplate(exampleActivityTemplate);
		if(list == null || list.size() == 0)
			return new Result(ErrorType.ACTIVETEMPLATE_NOT_EXIST);
		
		Activity activity = new Activity();
		activity.setCreateTime(new Date());
		activity.setActivityTemplate(list.get(0));
		activity.setUrl(url);
		if(priority != null)
			activity.setPriority(Integer.parseInt(priority));
		else
			activity.setPriority(null);
		activity.setMember(member);
		accessService.saveActivity(activity);
		
		if(activityParams != null)
		{
			for(int i=0;i<activityParams.length;i++)
			{
				ActivityTemplateParam param = activityParams[i];
				param.setActivity(activity);
				accessService.saveActivityTemplateParam(param);
			}
		}
		
		if(mediaItems != null)
		{
			for(int i=0;i<mediaItems.length;i++)
			{
				ActivityMediaItem item = mediaItems[i];
				item.setActivity(activity);
				accessService.saveActivityMediaItem(item);
			}
		}
		return new Result(activity.getActivityId());
	}
}
